//AvenirSQL的连接信息 连接池(后续)
const { SUCCESS } = require('./common/constants');
const { getSign, toLog, delQuotation } = require('./common/common');
const libcu = require('libcu');
const moment = require('moment');
class Conn {
    constructor() {
        //20201230 删除了默认的签名 test
        this.connList = {};     //数据类型 sign : {user ,password ,createTime}
        this.connList.test = {};            //可以考虑注释 测试dtest.js专用
        this.signValidTime = (ini.db.signValidTime > 10 && ini.db.signValidTime < 100) ? ini.db.signValidTime : 100;
        setInterval(async () => {
            await this.checkInvalidSign();
        }, (this.signValidTime / 10) * 1000);
    }

    //存放连接的用户信息
    async setUser(info, user, password) {
        toLog("开始处理签名 info = ", info);
        let now = moment().valueOf();
        //只有root是不去查数据库的
        if (!user || !password) {
            throw ("BAD_USER");
        }
        if (user === 'root') {
            let decode = libcu.cipher.AesDecode(password);
            if (!password || delQuotation(decode) != '123456') {
                throw ("BAD_USER");
            }
            let res = getSign(info);
            if (!this.connList[res]) {
                this.connList[res] = {
                    user,
                    password,
                    createTime: now,
                };  //存放用户信息
                throw ({ code: SUCCESS, data: res });
            } else {
                throw ('SYSTEM_BUSY');
            }
        } else {
            //没签名查不了库啊 所以这里先拿签名
            let sign = getSign(info);
            //拿完签名需要缓存 否则后续会报未登录的错误
            this.connList[sign] = {
                user,
                password,
                createTime: now,
            };
            let todo = `select * from User.user  where name = '${user}' and password = '${password}'`;
            try {
                let par = sql.parseSql(todo);
                await sql.doSql(par, sign, false);
            } catch (error) {
                toLog("拿到的值为 ", error);
                if (error && (error.code === 0 || error.code === 'AVENIR_SUCCESS')) {
                    if (!error.data || error.data.length === 0) {
                        //没查到数据
                        toLog("不存在该用户");
                        delete this.connList[sign];
                        throw ("USER_NOT_FOUND");
                    }
                    throw ({ code: SUCCESS, data: sign });
                }
                throw (error);
            }

        }


    }

    async checkSign(sign) {
        let now = moment().valueOf();
        if (!sign) {
            throw ('LACK_OF_SIGN');
        }
        if (!this.connList[sign]) {
            throw ("NOT_CONNECTED");
        }
        this.connList[sign].createTime = now;       //20201230 增加签名更新时间
        toLog(`更新了签名的有效期 sign = ${sign}:`, this.connList[sign]);
        return 0;
    }

    //判断是不是超级用户
    isRoot(sign) {
        if (this.connList[sign]) {
            if (this.connList[sign].user === 'root') {
                return true;
            }
            return false;
        } else {
            throw ("NOT_CONNECTED");
        }
    }

    async checkInvalidSign() {
        let now = moment().valueOf();
        for (let key in this.connList) {
            if (moment(now).diff(this.connList[key].createTime, 'seconds') > this.signValidTime) {
                toLog(`清理了签名 sign = ${key}:`, this.connList[key]);
                delete this.connList[key];
            }
        }
    }

}

module.exports = Conn;
